<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;padding-top: 20px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-button type="warning" @click="showGiveTable">精准发放</el-button>
        </el-form-item>

        <el-form-item>
          <span>状态：</span>
          <el-radio-group v-model="selectOptions.status" @change="currentChange">
            <el-radio-button v-for="(item, index) in [['all', '全部'],[1, '正常'],[0, '过期'],[-1, '作废']]" :label="item[0]" name="status" :key="index">{{ item[1] }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>

    </el-col>
    <!--列表-->
    <el-table :data="lists" highlight-current-row v-loading="listLoading" style="width: 100%;" class="main_table" element-loading-text="玩命请求中。。。">

      <el-table-column label="编号" width="65">
        <template slot-scope="scope">{{scope.row.id}}</template>
      </el-table-column>

      <el-table-column label="描述"  width="200">
        <template slot-scope="scope">
          <el-tag :type="{'1': 'primary', '2': 'success', '3': 'danger'}[scope.row.type]">
            {{ {'1': '满减', '2': '满折', '3': '免单'}[scope.row.type] }}
          </el-tag> 
          {{scope.row.title}}
          <div style="font-size:8px;">{{scope.row.desc}}</div>
        </template>
      </el-table-column>

      <el-table-column label="功能" width="140">
        <template slot-scope="scope">
          <div>满:{{ (scope.row.discount_scale/100).toFixed(2) }}元</div>
          <div v-if="scope.row.type==1">减:{{ (scope.row.discount_do/100).toFixed(2) }}元</div>
          <div v-if="scope.row.type==2">
            减:{{ (scope.row.discount_do/10).toFixed(1) }}折 <br/>
            最多:{{ (scope.row.discount_max/100).toFixed(2) }}元
          </div>
          <div v-if="scope.row.type==3">不要钱</div>
        </template>
      </el-table-column>

      <el-table-column label="领取" width="160">
        <template slot-scope="scope">
          <div>
            库存: <span v-if="scope.row.num==-1">无限</span>
                  <span v-else-if="scope.row.num==0"><b>已停产</b></span>
                  <span v-else>{{ scope.row.num }}张</span>
          </div>
          <div>
            单人每日: {{ scope.row.pull_once }}张
          </div>
          <div>
            单人上限: {{ scope.row.pull_max }}张
          </div>
          <b>{{ ['手动', '全平台自动发放', '新用户自动发放'][scope.row.auto] }}</b>
        </template>
      </el-table-column>

      <el-table-column label="当前状态" width="100">
        <template slot-scope="scope">
          {{ {'-1': '废弃', '0': '过期', '1': '正常'}[scope.row.status] }}
        </template>
      </el-table-column>

      <el-table-column label="所属卷包" prop="coupons_pkg_ids" width="120" :formatter="showPkgIds">
      </el-table-column>

      <el-table-column label="跳转说明" prop="jump_to">
      </el-table-column>

      <el-table-column label="保质期" width="180">
        <template slot-scope="scope">
          <div v-if="scope.row.start_time==0">
            {{ (scope.row.end_time / 86400).toFixed(2) }}天
          </div>
          <div v-else>
            {{ formatTime(scope.row.start_time) }}
            <br />
            {{ formatTime(scope.row.end_time) }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="CU_时间"  width="180">
        <template slot-scope="scope">
          {{scope.row.create_time}} <br/>
          {{scope.row.update_time}}
        </template>
      </el-table-column>

      <el-table-column label="操作" style="text-align:right;">
        <template slot-scope="scope" v-if="scope.row.status==1">
          <el-button type="warning" class="fa fa-ban" @click="set(scope.row.id, 'stop')">停产</el-button>
          <el-button type="danger" icon="delete" @click="set(scope.row.id, 'delete')">作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--精准发放优惠卷-->
    <el-dialog title="精准发放优惠卷" v-model="exactGiveShow" :close-on-click-modal="false">
      <el-form :model="giveUserCoupons" label-width="120px">
        <el-form-item label="用户uid（多个）">
          <template slot-scope="scope">
            <div style="width: 500px;display: inline-block;">
              <el-input type="text" :rows="4" v-model="giveUserCoupons.userIds" auto-complete="on"></el-input>
            </div>
            <p>
              <span style="margin-left: 10px;color: red">例如：1,2,3,4,5(**用英文逗号**)</span>
            </p>
          </template>
        </el-form-item>

        <el-form-item label="优惠卷id">
          <template slot-scope="scope">
            <div style="width: 300px;display: inline-block;">
              <el-input v-model="giveUserCoupons.coupons_id" auto-complete="on"></el-input>
            </div>
            例如：59<span style="margin-left: 10px;color: red">(输入数字)</span>
          </template>
        </el-form-item>

        <el-form-item label="发放记录">
          <template slot-scope="scope">
            <div style="margin-bottom: 4px;" v-for="(item, index) in sendLog">
              <span style="width: 390px;display: inline-block;"><el-input type="text" :rows="4" v-model="item.to_uids" auto-complete="on"></el-input></span>
              <span style="width: 100px;display: inline-block;margin-left: 10px"><el-input type="text" :rows="4" v-model="item.coupons_id" auto-complete="on"></el-input></span>
            </div>
          </template>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="exactGiveShow = false">取消</el-button>
        <el-button type="primary" @click.native="giveCouponsToUser">发放</el-button>
      </div>
    </el-dialog>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
        <el-pagination
          @current-change="currentPageChange"
          :page-size="30"
          layout="prev, pager, next, jumper"
          :total="total" style="float:right;" :current-page="parseInt(selectOptions.page)">
        </el-pagination>
        <span style="float: right;margin-top: 6px;margin-right: 5px">共 {{total}} 条数据</span>
      </el-col>
  </section>
</template>
<script>
  import NProgress from 'nprogress'
  import util from '../../util'
  import { apiTree } from '../../apiTree'

  export default {
    data() {
      return {
        filters: {},
        lists: [],
        total: 0,
        page: 1,
        selectOptions: {
          page: this.$route.query.page !== undefined ? this.$route.query.page : 1,
          status: this.$route.query.status !== undefined ? this.$route.query.status : 'all'
        },
        listLoading: false,
        exactGiveShow: false,
        giveUserCoupons: {
          'userIds': '',
          'coupons_id': '0'
        },
        sendLog: '',
        exactGiveSuccessShow: false
      }
    },
    methods: {
      // 选项卡选择
      currentChange() {
        this.$router.push({path: this.$route.path, query: this.selectOptions})
      },
      currentPageChange(val) {
        this.selectOptions.page = val
        this.$router.push({path: this.$route.path, query: this.selectOptions})
      },
      // 修改时间
      formatTime(_time) {
        return util.formatDate.format(new Date(_time * 1000), 'yyyy-MM-dd hh:mm:ss');
      },
      showPkgIds(row) {
        return row.coupons_pkg_ids === '0' ? '无' : row.coupons_pkg_ids
      },
      // 发放优惠卷弹窗
      showGiveTable() {
        this.giveUserCoupons = {
          'userIds': '',
          'coupons_id': '0'
        }
        apiTree('coupons/index', 'coupons/adminSendLog', this.giveUserCoupons).then((res) => {
          this.sendLog = res.d.data
        });
        this.exactGiveShow = true;
      },
      // 精准发放给用户优惠卷
      giveCouponsToUser() {
        let _error = 0;
        if (util.isEmpty(this.giveUserCoupons.userIds)) {
          this.$message.error('用户uid为空');
          _error = 1;
          return;
        }
        let _t = this.giveUserCoupons.userIds.split(',');
        _t.forEach((val) => {
          if (!util.isInt(val)) {
            this.$message.error('用户uid不为数字');
            _error = 1;
            return;
          }
        });
        if (util.isEmpty(this.giveUserCoupons.coupons_id) || !util.isInt(this.giveUserCoupons.coupons_id) || parseInt(this.giveUserCoupons.coupons_id) <= 0) {
          this.$message.error('优惠卷id错误');
          _error = 1;
          return;
        }
        if (_error === 1) {
          return
        }
        this.$confirm(`确认是这些用户吗 ?`, '很重要的提示', {
          confirmButtonText: '我确定要这样做',
          cancelButtonText: '想想还是算了',
          type: 'warning'
        }).then(() => {
          apiTree('coupons/index', 'coupons/send', this.giveUserCoupons, 'POST').then((res) => {
            if (res.s === 1) {
              this.$alert('请等待2s后关闭......', '标题名称', {
                confirmButtonText: '关闭',
                callback: action => {
                  this.exactGiveShow = false;
                }
              });
            } else {
              this.$alert('出问题了')
            }
          })
        })
      },
      views: function () {
        this.listLoading = true
        NProgress.start()
        let para = this.$route.query
        if (util.isEmptyObject(para)) {
          this.selectOptions = {
            page: 1,
            status: 'all'
          }
        }
        apiTree('coupons/index', 'coupons/index', para).then((res) => {
            this.lists = res.d.data
            this.total = parseInt(res.d.total_num)
            this.listLoading = false
            NProgress.done();
        })
      },
      set: function ($id, $cmd) {
        var msg = {'stop': '停产', 'delete': '销毁'}[$cmd]
        this.$confirm(`确认要把这个优惠券${msg} ?` , '很重要的提示', {
          confirmButtonText: '我确定要这样做',
          cancelButtonText: '想想还是算了',
          type: 'warning'
        }).then(() => {
          apiTree('coupons/index', 'coupons/set', {'id': $id, 'cmd': $cmd}).then((res) => {
            if (res.s === 1) {
              this.$message({
                message: '命令执行完毕',
                type: 'success'
              })
              this.views()
            } else {
              this.$alert('出问题了')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '别瞎戳'
          });
        })
      }
    },
    watch: {
      $route: 'views'
    },
    mounted() {
      this.views()
    }
  }
</script>
